<?php

namespace app\admin\controller\facrm\apps;

use app\common\controller\Backend;
use think\Db;
use think\Queue;
use think\Validate;

/**
 * 短息模板
 * @icon fa fa-tags
 */
class Sms extends Backend
{

    protected $key = "sms_tpl_setting_lists";
    protected $addon_config = array();
    protected $noNeedRight = ['getfield', 'selectpage'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\facrm\Setting();
        $this->modelList = ['customer' => __('客户'), 'contacts' => __('联系人'), 'clues' => __('线索')];
        $this->view->assign('modelList', $this->modelList);
    }

    /**
     * 查看列表
     * @return string|\think\response\Json
     * @throws \think\Exception
     */
    public function index()
    {

        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                $this->request->request(['custom' => ['key' => $this->key]]);
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->where('key', $this->key)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $total = $this->model
                ->where($where)
                ->where('key', $this->key)
                ->order($sort, $order)
                ->count();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $source = $this->request->param('source', 'customer');
        $this->view->assign('source', $source);

        return $this->view->fetch();
    }

    /**
     * 添加
     * @return mixed
     */
    public function add()
    {

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params['content']) {
                $params['values']['content'] = $params['content'];
                unset($params['content']);
            }

            if (empty($params['values'])) $this->error();
            $this->request->post(['row' => array_merge($params, [
                'values' => json_encode($params['values'])
            ])]);
        }
        $this->assign('template_data', json_encode($this->getfield("customer", false)));
        $this->addon_config = get_addon_config('facrm');
        $this->view->assign("recordTypeList", $this->addon_config['record_type']);
        $this->view->assign('key', $this->key);
        return parent::add();
    }

    /**
     * 修改
     * @return mixed
     */
    public function edit($ids = null)
    {

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params['content']) {

                $params['values']['content'] = $params['content'];
                unset($params['content']);
            }

            if (empty($params['values'])) $this->error();
            $this->request->post(['row' => array_merge($params, [
                'values' => json_encode($params['values'])
            ])]);
        }
        $this->assign('template_data', json_encode($this->getfield("customer", false)));
        $this->view->assign('key', $this->key);
        $this->addon_config = get_addon_config('facrm');
        $this->view->assign("recordTypeList", $this->addon_config['record_type']);
        return parent::edit($ids);
    }

    /**
     * 发短息
     */
    public function send()
    {

        $data = $this->request->param('data');
        $data = json_decode($data, true);
        $types_data = array();//发送对象数据，如客户，联系人
        if ($data && $data['types']) {
            $auth = new \addons\facrm\library\Auth();
            //TODO 还可以精简，为了明了，暂时不做
            switch ($data['types']) {
                case "customer":
                    $custModel = new \app\admin\model\facrm\Customer();
                    $types_data = $custModel->find($data['typesid']);
                    if (!$auth->checkCustomerAuth($types_data, $this->auth)) {
                        $this->error(__('您没有权限'));
                    }
                    break;
                case "business":
                    $custModel = new \app\admin\model\facrm\Customer();
                    $types_data = $custModel->find($data['customer_id']);
                    if (!$auth->checkCustomerAuth($types_data, $this->auth)) {
                        $this->error(__('您没有权限'));
                    }
                    break;
                case "contacts":
                    $contactsModel = new \app\admin\model\facrm\customer\Contacts();
                    $types_data = $contactsModel->find($data['typesid']);
                    if (!$types_data) break;
                    if (!$auth->checkCustomerAuth($types_data['customer_id'], $this->auth)) {
                        $this->error(__('您没有权限'));
                    }
                    break;
                case "clues":
                    $custModel = new \app\admin\model\facrm\Clues();
                    $types_data = $custModel->find($data['typesid']);
                    if (!$auth->checkCluesAuth($types_data, $this->auth)) {
                        $this->error(__('您没有权限'));
                    }
                    break;
                default:
                    break;
            }
        }
        if ($types_data){
            $types_data = $types_data->toArray();
        }

        $sms_id = $this->request->param('sms_id', '', 'intval');
        $config_row = array();//模板配置
        if ($sms_id) {
            $config_row = $this->model
                ->where('key', $this->key)->find($sms_id);

            if (!$config_row) $this->error(__("短息模板不存在"));

            $config_row['values'] = json_decode($config_row['values'], true);
            $tpl = $config_row['values'];
            $tpl['content'] = is_array($tpl['content']) ? $tpl['content'] : (array)json_decode($tpl['content'], true);
            //封装msg
            $temp_val = array();
            foreach ($tpl['content'] as $item) {
                if ($item['value']) {
                    $value = $item['key'] == 'diy_text' ? $item['def_val'] : '';
                    $value = (isset($types_data[$item['key']]) && $types_data[$item['key']] && !$value ? $types_data[$item['key']] : $item['def_val']);
                    $temp_val[$item['value']] = $value;
                }
            }
            $config_row['tpl_content'] = __($tpl['tpl_content'], $temp_val);//处理之后的模板数据
        }


        if ($this->request->isPost()) {
            $row = $this->request->post('row/a');
            if ($row['mobile']) {
                if (!Validate::is($row['mobile'], "/^1[3456789]{1}\d{9}$/")) {
                    $this->error(__('手机有误'));
                }
                if (!$config_row) $this->error(__('短息模板不存在'));
                //短息队列
                $data = array_merge($data, [
                    'mobile' => $row['mobile'],
                    'template' => $config_row['values']['tpl_id'],
                ]);

                $data['msg'] = $temp_val;

                Queue::push("addons\\facrm\\library\\queue\\SmsJob", $data);

                //队列end
                if (true) {
                    //param_data types类型如customer,contacts| typesid对应的ID
                    //send_data发送的内容
                    //types_data 当前对象的数据
                    $row['create_user_id'] = $this->auth->id;//用于标明是谁发送的
                    $row['content'] = $config_row['tpl_content'] ? $config_row['tpl_content'] : $row['content'];
                    $row['record_type']=isset($config_row['values']['record_type']) ? $config_row['values']['record_type'] : 0;//跟进类型
                    hook("facrm_send_sms_success", array('param_data' => $data, 'send_data' => $row, 'types_data' => $types_data));
                    $this->success();
                }
            } else {
                $this->error(__('Invalid parameters'));
            }
        }


        return $this->view->fetch('', ['row' => $config_row, 'types_data' => $types_data]);

    }

    /**
     * 批量发送
     * @param $data ['types'] //发送配置，types：customer，contacts
     * @param $data ['typesid'] //对象集合ID，多个以逗号隔开
     * @param $data ['content'] //短息预览
     * @param $data ['create_user_id'] //发送人ID
     * @param $data ['record_type'] //跟进类型ID
     * @param $data ['sms_id'] //短息模板ID
     * @return string
     */
    public function sends()
    {

        $data = $this->request->param('data');
        $data = json_decode($data, true);

        if ($this->request->isPost()) {
            $row = $this->request->post('row/a');

            //TODO 未判断选择客户和联系人的权限 批量发送可以是运营人员组发送
            //队列
            $row['create_user_id'] = $this->auth->id;

            $data = array_merge($data, $row);
            Queue::push("addons\\facrm\\library\\queue\\SmssJob", $data);
            $this->success();
        }
        $sms_id = $this->request->param('sms_id', '', 'intval');
        $config_row = array();
        if ($sms_id) {
            $config_row = $this->model
                ->where('key', $this->key)->find($sms_id);
            if (!$config_row) $this->error(__("短息模板不存在"));

            $config_row['values'] = json_decode($config_row['values'], true);

            switch ($data['types']) {
                case "customer":
                    $custModel = new \app\admin\model\facrm\Customer();
                    $types_data = $custModel->where('id', 'in', $data['typesid'])->find();
                    $types_data = $types_data->toArray();
                    break;
                case "contacts":
                    $contactsModel = new \app\admin\model\facrm\customer\Contacts();
                    $types_data = $contactsModel->where('id', 'in', $data['typesid'])->find();
                    if (!$types_data) break;
                    break;
                case "clues":
                    $custModel = new \app\admin\model\facrm\Clues();
                    $types_data = $custModel->where('id', 'in', $data['typesid'])->find($data['typesid']);
                    $types_data = $types_data->toArray();
                    break;
                default:
                    break;
            }
            $tpl = $config_row['values'];
            $tpl['content'] = is_array($tpl['content']) ? $tpl['content'] : (array)json_decode($tpl['content'], true);
            //封装msg
            $temp_val = array();
            foreach ($tpl['content'] as $item) {
                if ($item['value']) {
                    $value = $item['key'] == 'diy_text' ? $item['def_val'] : '';
                    $value = (isset($types_data[$item['key']]) && $types_data[$item['key']] && !$value ? $types_data[$item['key']] : $item['def_val']);
                    $temp_val[$item['value']] = $value;
                }
            }
            $config_row['tpl_content'] = __($tpl['tpl_content'], $temp_val);//处理之后的模板数据
        }


        return $this->view->fetch('', ['row' => $config_row, 'types_data' => []]);
    }

    /**
     * 获取参数字段
     * @param string $types types：customer，contacts
     * @internal
     */
    public function getfield($types = "customer", $return_ajax = true)
    {
        $fieldlist=\addons\facrm\library\Helper::getfield($types,'*',['diy_text'=>__("自定义文本")]);

        if ($return_ajax) {
            $this->success("", null, $fieldlist);
        }
        return $fieldlist;
    }
    /**
     * 选择模板
     * @Internal
     * @return \think\response\Json
     */
    public function selectpage()
    {
        $this->request->request(['custom' => ['key' => $this->key,'status'=>1]]);
        return parent::selectpage(); // TODO: Change the autogenerated stub
    }
}